﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcEngine.Core.Localization;

using MvcEngine.Core;
using MvcEngine.Core.Content;
using MvcEngine.Core.Website;
using MvcEngine.Core.Account;

namespace MvcEngine.Mvc.Models.ViewModels
{
    public class MvcEngineModel
    {
        public AntiForgeryToken AntiForgeryToken { get; set; }

        public Site Site 
        {
            get { return SiteContext.Current.Site; } 
        }

        public Page Page 
        {
            get { return SiteContext.Current.CurrentPage; }
        }

        public User User 
        {
            get { return UserContext.Current.User; } 
        }

        public string ViewName { get; set; }

        #region Private fields
        
        private readonly Dictionary<string, object> modelValues = new Dictionary<string, object>();
        private readonly Dictionary<Type, object> modelItems = new Dictionary<Type, object>();

        #endregion

        public MvcEngineModel(MvcEngineModel model) 
        {
            this.modelItems = model.modelItems;
            this.modelValues = model.modelValues;
            this.AntiForgeryToken = model.AntiForgeryToken;
#warning Think about...
            //this.User = model.User;
        }

        public static MvcEngineModel New() 
        {
            return new MvcEngineModel();
        }

        public MvcEngineModel()
        {
            
        }

        public void AddModelItem<T>(T modelItem) where T : class
        {
            modelItems[typeof(T)] = modelItem;
        }

        public T GetModelItem<T>() where T : class
        {
            if (modelItems.ContainsKey(typeof(T)))
                return modelItems[typeof(T)] as T;

            return null;
        }

        public object GetModelValue(string key)
        {
            if (string.IsNullOrEmpty(key))
                return null;
            if (modelValues.ContainsKey(key))
                return modelValues[key];
            return "Not found key: " + key;
        }

        public void SetModelValue(string key, object value)
        {
            modelValues[key] = value;
        }

        public string Localize(string key)
        {
            return Localize(key, key);
        }

        public string Localize(string key, string defaultValue)
        {
            return ResourceReader.Current.GetString(key, defaultValue);
        }
    }
}
